package gob.pe.inei.esvit.web.validator;

import gob.pe.inei.esvit.bll.dsl.adm.ADMMUsuarioDSL;
import gob.pe.inei.esvit.ebl.entity.adm.ADMMUsuario;
import gob.pe.inei.esvit.ebl.types.adm.ADMMUsuarioDCT;
import gob.pe.inei.esvit.lib.security.SSD;
import gob.pe.inei.esvit.web.bean.LoginBean;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

@Repository(value = "loginValidator")
public class LoginValidator implements Validator {

	@Autowired
	private ADMMUsuarioDSL usuarioDSL;

	public void setVariableDSL(ADMMUsuarioDSL usuarioDSL) {
		this.usuarioDSL = usuarioDSL;
	}

	public boolean supports(Class<?> typeClass) {
		return ADMMUsuario.class.isAssignableFrom(typeClass);
	}

	public void validate(Object target, Errors errors) {
		LoginBean bean = (LoginBean) target;
		if (bean.getUsername().trim().isEmpty()) {
			errors.rejectValue("username", "username.empty");
			return;
		}
		if (bean.getPassword().trim().isEmpty()) {
			errors.rejectValue("password", "password.empty");
			return;
		}
		List<ADMMUsuario> list = usuarioDSL.findAllBy(ADMMUsuarioDCT.cCodGenUsu, bean.getUsername());
		if (list == null || list.size() == 0) {
			errors.rejectValue("username", "username.error");
			return;
		}
		ADMMUsuario var = list.get(0);
		String password = new String(var.getcPasSegUsu());
		String newPassword = SSD.encrypt(bean.getPassword(), SSD.MD5);
		if (!newPassword.equals(password))
			errors.rejectValue("password", "password.error");
	}
}
